import fetch from "../../utils/fetch";
const globalData = getApp().globalData;
const userId = globalData.userInfo.id;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 'aiwowo',
    name: '艾窝窝',
    img: "http://image.hpcn21.com/upfiles/food/201410/2871/sa20150101225425.jpg",
    alias: null,
    heat_cal: "190.00 千卡",
    "热量(大卡)": 190.00,
    isCollect: true,
    showData: [{
        name: '碳水化合物',
        percent: 82.3,
        weight: 10.2
      },
      {
        name: '蛋白质',
        percent: 12.3,
        weight: 0.6
      },
      {
        name: '脂肪',
        percent: 5.4,
        weight: 0.1
      }
    ],
    elements: {},
    dpr: 2,
    r: 50, //环形半径
    centerPoint: { //环形中心
      x: 60,
      y: 60
    },
    // 记录食物相关的数据
    show: false,
    gramCurrentNumber: 100,
    gram: 100,
    tempGramCurrentNumber: 100, // 保存所有popup的初始值
    unitHeat: 0, // 当前选中的食物单位热量
    foodHeat: 0, // 当前选中的食物总热量
    selectedFood: {}, // 选中的食物
    foodRecord: [
    ], // 添加的食物
    recordDate: "",
    time: "早餐"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    console.log(options.recordDate);
    this.setData({
      recordDate:options.recordDate,
      time: options.time
    })
    //获取分辨率
    this.data.dpr = wx.getSystemInfoSync().pixelRatio;
    fetch(`/food/detail?foodId=${options.foodId}&userId=${userId }`, ).then(res => {
      const {
        alias,
        name,
        foodcate,
        heat_cal,
        id,
        img,
        elements,
        nutritions,
        isCollect
      } = res.data;
      let elementArr = [];
      Object.keys(elements).forEach(key => {
          let o = {};
          o.name = key;
          o.weight = elements[key]!== null ? elements[key] : '—';
          elementArr.push(o)
      })
      this.setData({
        name,
        foodcate,
        heat_cal,
        id,
        img,
        alias,
        elements: elementArr,
        nutritions,
        isCollect
      })
    })
    this.initCanvas()
  },
  // 画环形统计图
  initCanvas() {
    wx.nextTick(() => {
      wx.createSelectorQuery()
        .select('#circle')
        .fields({
          node: true,
          size: true
        })
        .exec(res => {
          const canvas = res[0].node;
          const ctx = canvas.getContext('2d');
          const dpr = this.data.dpr;
          // 根据分辨率设置画布宽高
          canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          ctx.scale(dpr, dpr)

          this.canvas = canvas
          this.ctx = ctx

          if (ctx) {
            this.drawArc();
          }
        })
    })
  },
  drawArcs(sAngle, eAngle, border, color) {
    // r：半径 
    // centerPoint：圆心坐标 
    // ctx：canvas 实例
    const {
      r,
      centerPoint
    } = this.data;
    const { x, y } = centerPoint;
    const ctx = this.ctx;
    // 开始创建一个绘画路径
    ctx.beginPath()
    // 设置弧线宽度
    ctx.lineWidth = border
    // 设置弧线的颜色
    ctx.strokeStyle = color
    // 创建一条弧线
    ctx.arc(x, y, r, sAngle, eAngle, false)
    // 画出弧线的边框
    ctx.stroke()
    // 关闭绘画路径
    ctx.closePath()
  },
  //各弧段百分比
  drawArc() {
    let showData = this.data.showData;
    const nutritions = this.data.nutritions;
    showData[0].weight = parseFloat(nutritions['碳水化合物(克)']) ? parseFloat(nutritions['碳水化合物(克)']) : 0.0;
    showData[1].weight = parseFloat(nutritions['蛋白质(克)']) ? parseFloat(nutritions['蛋白质(克)']) : 0.0;
    showData[2].weight = parseFloat(nutritions['脂肪(克)']) ? parseFloat(nutritions['脂肪(克)']) : 0.0;
    // 各段弧百分比
    let sum = 0;
    showData.forEach(item => {
      sum += item.weight;
    });
    showData.forEach(item => {
      item.percent = parseFloat(((item.weight / sum) * 100).toFixed(2));
    });
    showData[0].percent = (100 - showData[1].percent - showData[2].percent).toFixed(2);
    // 百分比数组
    let ratios = []
    showData.forEach(item => {
      ratios.push(item.percent);
    });
    this.setData({
      showData: showData
    })
    // 各段弧颜色
    const colors = ['#2A9D8F', '#E9C46A', '#F4A261']
    // 每段弧开始弧度
    let sAngle = 0
    ratios.forEach((item, index) => {
      // 各段线的弧度
      // 2*Math.PI*弧线百分比/100
      const angle = (item * Math.PI) / 50
      // 结束弧度，需要加上上一段弧线的结束弧度
      const eAngle = sAngle + angle
  
      this.drawArcs(sAngle, eAngle, 10, colors[index])
      sAngle = eAngle
    })
  },
  changeCollect(){
    const isCollect = this.data.isCollect;
    if(!isCollect){
      fetch(`/collect?userId=${userId}&id=${this.data.id}&collectType=food`).then(res => {
        if (res.code === 200) {
          this.setData({
            isCollect: true
          });
        }
      })
    }else{
      fetch(`/collect/uncollect?userId=${userId}&id=${this.data.id}&collectType=food`).then(res => {
        if (res.code === 200) {
          this.setData({
            isCollect: false
          });
        }
      })
    }
  },
  showPopup(e) {
    const food = {};
    food.id = this.data.id;
    food.img = this.data.img;
    food.name = this.data.name;
    food.alias = this.data.alias;
    food.heat_cal = this.data.heat_cal;
    const  showData = this.data.showData;
    food.carbohydrate = showData[0].weight;
    food.protein = showData[1].weight;
    food.fat = showData[2].weight;
    const unitHeat = parseFloat(this.data.heat_cal.split(" ")[0]);
    this.setData({
      selectedFood: food,
      unitHeat,
      foodHeat: isNaN(unitHeat) ? 0 : unitHeat,
      gramCurrentNumber: this.data.tempGramCurrentNumber,
      show: true
    });
  },
  closePopup(){
    this.setData({
      show: false
    })
  },
  onClose(e) {
    const foodRecord = e.detail.foodRecord;
    this.setData({
      show: false,
      foodRecord
    });
    this.addRecord();
  },
  addRecord() {
    fetch('/foodRecord/add', {
      foodRecord: this.data.foodRecord
    }, 'post').then(res => {
      if (res.code === 200) {
        this.setData({
          show: false
        })
        wx.navigateTo({
          url: `../foodRecord/foodRecord?recordTime=${this.data.time}&recordDate=${this.data.recordDate}`,
        })
      }
    })
  },
})